package com.netease.financial.data.net;

import android.content.Context;

import com.netease.financial.common.constant.Constants;
import com.netease.financial.common.security.SecurityJNI;
import com.netease.financial.common.util.NfsLog;

import java.lang.reflect.Constructor;

import retrofit.RequestInterceptor;
import retrofit.RestAdapter;

/**
 * Created by wyf on 11/13/15.
 */
public class ApiServiceProvider {

    private static final String CLASS_NAME_APP_UPDATE_INFO_SERVICE_FLAVOR = "com.netease.financial.data.net.AppUpdateInfoServiceWrapper";

    public static NfsRestApiService getNfsRestApiService() {
        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                // 需要在header中添加NFS服务端预先提供的AppId,才能合法进行请求
                request.addHeader("AppId", SecurityJNI.getAppId());
            }
        };

        RestAdapter.LogLevel logLevel = NfsLog.DEBUG_MODE ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE;
        RestAdapter nfsRestAdapter = new RestAdapter.Builder()
                .setEndpoint(Constants.getNfsApiEndPoint())
                .setRequestInterceptor(requestInterceptor)
                .setLogLevel(logLevel)
                .build();

        return nfsRestAdapter.create(NfsRestApiService.class);
    }

    // 获取需要使用的更新接口对应的service，如果各个product flavor提供了自己的实例，则使用之，否则使用默认的service
    public static NfsRestApiService getAppUpdateInfoService(Context context, NfsRestApiService nfsRestApiService) {
        NfsRestApiService service;

        try {
            Class<?> classType = Class.forName(CLASS_NAME_APP_UPDATE_INFO_SERVICE_FLAVOR);
            Class<?>[] constructorParamTypes = {Context.class, NfsRestApiService.class};
            Object[] constructorParamValues = {context, nfsRestApiService};
            Constructor<?> constructor = classType.getConstructor(constructorParamTypes);
            service = (NfsRestApiServiceWrapper) constructor.newInstance(constructorParamValues);
        } catch (Exception e) {
            e.printStackTrace();
            service = nfsRestApiService;
        }

        return service;
    }

}
